package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket clientSocket = null;
    // 服务器的ip地址
    private String serverIp;
    // 服务器的端口号
    private int serverPort;

    public UdpEchoClient(String ip, int port) throws SocketException {
        // 由服务器随机分配一个空闲的端口号
        clientSocket = new DatagramSocket();
        serverIp = ip;
        serverPort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动 !");
        while(true) {
            // 1. 客户端输入请求
            Scanner scanner = new Scanner(System.in);
            System.out.print("->");
            String request = scanner.nextLine();
            // 2. 构造请求数据包 并 发送请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            clientSocket.send(requestPacket);
            // 3. 接收服务器发回的响应
            DatagramPacket responsePack = new DatagramPacket(new byte[2048],2048);
            clientSocket.receive(responsePack);
            // 将响应转换成字符串 并进行打印
            String response = new String(responsePack.getData(),0,responsePack.getLength());
            System.out.println(response);
        }
    }


    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 8080);
        client.start();
        System.out.println("断开连接 !");
    }
}
